package com.tools.cleanmaster.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.tools.ad.EntranceType;
import com.tools.ad.ui.view.FontTextView;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.cpucool.CpuCoolInterface;
import com.tools.cleanmaster.cpucool.CpuCoolManager;
import com.tools.cleanmaster.cpucool.CpuTempInfo;
import com.tools.cleanmaster.cpucool.widget.CpuAnimatorLayout;
import com.tools.cleanmaster.cpucool.widget.CpuAnimatorView;
import com.tools.cleanmaster.scenenew.SceneType;
import com.tools.cleanmaster.store.CpuCoolSharedPrefManager;
import com.tools.cleanmaster.store.ResultPageSharedPrefManager;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.ui.base.ResultSingleActivity;
import com.tools.cleanmaster.ui.card.factory.CardDataHelper;
import com.tools.cleanmaster.ui.card.ui.ResultSingleCardLayout;
import com.tools.cleanmaster.ui.view.functionpage.AppsIconListView;
import com.tools.cleanmaster.ui.view.header.HeadHelper;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import java.util.List;

/**
 * yrickwong on 16/3/18.
 */
public class CpuCoolActivity extends ResultSingleActivity implements View.OnClickListener, CpuCoolInterface.GetCpuTempListener,
        CpuAnimatorView.CpuAnimatorListener {


    private AppsIconListView mAppIconListView;
    private Button mStartButton;
    private CpuAnimatorLayout mCpuAnimatorLayout;
    private CpuAnimatorView mCpuAnimatorView;
    private LinearLayout mTemperatureAllview;
    private LinearLayout mTemperatureLayout;
    private FontTextView mTemperatureText;
    private FontTextView mTemperatureOverheated;
    private FontTextView mTemperatureDrop;
    private FontTextView mTemperatureDropDegree;
    private TextView mTvTitle;
    private View mButtonContent;
    private GridView mGridView;
    private double mCpuTempValue = 0;
    private double mCpuOptimizeTempValue = 0;
    private int mCpuDropValue;
    private boolean mIsNoApp = false;

    private String mFrom = "unknow";
    private boolean mIsCoolNowClicked = false;

    private List<ProcessItem> mProcessItems;

    private static int OVERHEATED_TEMPERATURE = 5;

    private int mTemperatureDropLength;
    private boolean isProtected;

    public static final String KEY_PHONEACC_NO_APP = "from_phone_add_no_app";
    public static final String KEY_STRING_INTENT_CPU_TEMP = "cpu_temp_value";
    public static final String KEY_STRING_INTENT_CPU_OPTIMIZE_TEMP = "cpu_optimize_temp_value";

    private static final int STATE_IDLE = 0;
    private static final int STATE_START = 1;
    private static final int STATE_FINISHED = 2;
    private int mCurrentState = STATE_IDLE;
    private static final int MARK_DELAY = 800;
    private View cpuContainer;
    private LinearLayout cpuFullScreenLayout;

    @Override
    protected void setCardHeadTitle() {
        if (mResultMultiCardLayout != null) {
            mResultMultiCardLayout.setHeadTitle(getString(R.string.landingpage_header_title));
        }
    }

    @Override
    protected void hideBackground() {
        cpuContainer.setVisibility(View.GONE);
        HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_resultpage_title)
                .hideSettingButton().setBackgroundColor();
    }

    @Override
    protected EntranceType getEntranceType() {
        return EntranceType.LANDING;
    }

    @Override
    public ResultPageType getResultPageType() {
        return ResultPageType.MultiCardPage;
    }

    @Override
    protected void setContentView(Bundle savedInstanceState) {
        setContentView(R.layout.cpu_cool_activity);
        StatusBarUtil.setTranslucent(this);

        initViews();
        initAd();

        Intent intent = getIntent();
        if (intent != null) {
            mCpuTempValue = intent.getDoubleExtra(KEY_STRING_INTENT_CPU_TEMP, 0);
            mCpuOptimizeTempValue = intent.getDoubleExtra(KEY_STRING_INTENT_CPU_OPTIMIZE_TEMP, 0);
            mIsNoApp = intent.getBooleanExtra(KEY_PHONEACC_NO_APP, false);
            String from = intent.getStringExtra("unknow");
            if (TextUtils.isEmpty(from)) {
                mFrom = "unknow";
            } else {
                mFrom = from;
            }
        }

        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.i("CpuCoolConstants", "from = " + mFrom);
        }

        if (CpuCoolManager.getInstance().isInProtectTime()) {
            mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.PROTECT_TIME);
            mTvTitle.setVisibility(View.GONE);
            mStartButton.setVisibility(View.GONE);
            isProtected = true;
            // 保护时间内，设置此次降温为0度
            CpuCoolSharedPrefManager.setCpuCoolLastTempDrop(0);
        } else if (mIsNoApp) {
            mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.PROTECT_TIME);
            mTvTitle.setVisibility(View.GONE);
            mStartButton.setVisibility(View.GONE);
            // 无发热应用时，设置此次降温为0度
            CpuCoolSharedPrefManager.setCpuCoolLastTempDrop(0);
        } else {
            CpuCoolManager.getInstance().addListener(this);
            boolean needUpdate = CpuCoolManager.getInstance().getNeedUpdateTem();
            CpuCoolManager.getInstance().startGetCpuTempAsync(true, needUpdate);
            if (needUpdate) {
                CpuCoolManager.getInstance().setNeedUpdateTem(false);
            }
            isProtected = false;
        }
    }

    private void initAd() {
        CardDataHelper.requestAd(getEntranceType());
    }

    private static final int PRO_FOUND = 11;
    private static final int MORE_SUGGSETION = 12;
    private static final int FUNCTION_NORMAL = 13;
    private static final int FUNCTION_NORMAL_RESULT = 14;

    private void changeTitle(int status) {
        switch (status) {
            case PRO_FOUND:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_problem_found)
                        .hideSettingButton();
                break;
            case MORE_SUGGSETION:
                if (ResultPageSharedPrefManager.isCloudResultPageSwitch(this)) {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_optimized)
                            .hideSettingButton();
                } else {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_suggestion)
                            .hideSettingButton();
                }
                break;
            case FUNCTION_NORMAL:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_checking_text)
                        .hideSettingButton();
                break;
            case FUNCTION_NORMAL_RESULT:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_resultpage_title)
                        .hideSettingButton();
                break;
        }
    }

    private void initViews() {
        changeTitle(PRO_FOUND);
        cpuContainer = findViewById(R.id.cpu_container);
        mStartButton = findViewById(R.id.start_cool_cpu);
        mStartButton.setText(R.string.cpu_cool_down_button_msg);
        mStartButton.setOnClickListener(this);
        mStartButton.setEnabled(false);

        mTvTitle = findViewById(R.id.pull_to_refresh_text);
        mGridView = findViewById(R.id.app_icon_grid);
        mGridView.setVerticalFadingEdgeEnabled(true);
        mGridView.setFadingEdgeLength((int) getResources().getDimension(
                R.dimen.cpu_icon_list_fading_edge));

        mCpuAnimatorLayout = findViewById(R.id.cpu_animator_layout);
        mCpuAnimatorView = findViewById(R.id.cpu_animator_view);
        mCpuAnimatorView.setCpuAnimationListener(this);

        mTemperatureAllview = findViewById(R.id.temperature_allview);

        mTemperatureText = findViewById(R.id.temperature_text);
        mTemperatureLayout = findViewById(R.id.temperature_layout);
        mTemperatureOverheated = findViewById(R.id.temperature_overheated_text);

        mAppIconListView = findViewById(R.id.run_app_backview);

        mTemperatureDrop = findViewById(R.id.temperature_text_drop);
        mTemperatureDropDegree = findViewById(R.id.temperature_text_drop_degree);

        mTemperatureDropLength = getResources().getDimensionPixelSize(R.dimen.cpu_scan_text_size);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.start_cool_cpu) {
            CardDataHelper.requestAd(EntranceType.LANDING_INTERSTITIAL);

            mIsCoolNowClicked = true;
            mCurrentState = STATE_START;
            CpuCoolManager.getInstance().startCpuCoolAsync(mProcessItems);
            mAppIconListView.clearAppAnimation(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    mTvTitle.setText(R.string.killing_apps_cooldown_cpu);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (mAppIconListView != null) {
                        mAppIconListView.setVisibility(View.GONE);
                    }
                    if (mStartButton != null) {
                        mStartButton.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            mStartButton.setEnabled(false);
            ObjectAnimator rotateAnim1 = ObjectAnimator.ofFloat(mCpuAnimatorLayout, "rotationY", 0,
                    90);
            ObjectAnimator rotateAnim2 = ObjectAnimator.ofFloat(mCpuAnimatorLayout, "rotationY",
                    90, 0);
            rotateAnim1.setDuration(200);
            rotateAnim2.setDuration(200);
            rotateAnim1.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mTemperatureAllview.setVisibility(View.GONE);
                    mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.ROTATE);
                }
            });
            rotateAnim2.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.COOLING);
                }
            });
            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.play(rotateAnim1).before(rotateAnim2);
            animatorSet.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CpuCoolManager.getInstance().removeListener(this);
    }

    @Override
    public void onGetCpuTempDone(CpuTempInfo info) {
        mProcessItems = info.getProcessItems();
        mAppIconListView.setAppsIcons(mProcessItems);
        double dTemp = info.getCpuTemp();
        float f = (float) dTemp;
        boolean overheated = (f >= OVERHEATED_TEMPERATURE);
        mCpuAnimatorView.setOverHeated(overheated);
        mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.SCAN_END);
        mTvTitle.setText(Html.fromHtml(getString(R.string.running_apps_heatingup_cpu, String.valueOf(mProcessItems.size()))));
        mTemperatureText.setText(Float.toString(f));
        if (overheated) {
            mTemperatureOverheated.setText(R.string.cpu_temperature_state_overheated_msg);
        } else {
            mTemperatureOverheated.setText(R.string.cpu_temperature_state_normal_msg);
        }
    }

    @Override
    public void onMakeCpuCoolDone(double coolTemp, double lastTemp) {
        int nCpuTempValue = (int) mCpuTempValue == 0 ? (int) lastTemp
                : (int) mCpuTempValue;
        int nCpuTempOptimizeValue = (int) mCpuOptimizeTempValue == 0 ? (int) coolTemp
                : (int) mCpuOptimizeTempValue;
        mCpuDropValue = nCpuTempOptimizeValue;
        CpuCoolSharedPrefManager.setCpuCoolLastTime(System.currentTimeMillis());
        CpuCoolSharedPrefManager.setCpuCoolLastTemp(nCpuTempValue);
        CpuCoolSharedPrefManager.setCpuCoolLastTempDrop(nCpuTempOptimizeValue);
        mTemperatureDropDegree.setText(nCpuTempOptimizeValue + "°C");
        mCpuAnimatorView.setCoolDownFinished(true);
        // 设置执行CPU降温后，所杀的应用进程的保护时间
        CpuCoolManager.getInstance().setAppsProtect(mProcessItems);
        mCurrentState = STATE_FINISHED;
    }

    @Override
    public void onBackPressed() {
        CpuCoolManager.getInstance().removeListener(this);
        finish();
    }

    private void startShowCpuTemperature() {
        ViewHelper.setAlpha(mTemperatureLayout, 0);
        mTemperatureLayout.setVisibility(View.VISIBLE);
        ValueAnimator alpha = ObjectAnimator.ofFloat(mTemperatureLayout, "alpha", 0, 1);
        alpha.setDuration(200);

        ViewHelper.setAlpha(mTemperatureOverheated, 0);
        mTemperatureOverheated.setVisibility(View.VISIBLE);
        ValueAnimator alpha1 = ObjectAnimator.ofFloat(mTemperatureOverheated, "alpha", 0, 1);
        alpha1.setDuration(200);
        ValueAnimator translationY = ObjectAnimator.ofFloat(mTemperatureOverheated, "translationY",
                100, 0);
        translationY.setDuration(200);
        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(alpha1, translationY);

        alpha.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animatorSet.start();
            }
        });

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mStartButton.setEnabled(true);
            }
        });

        alpha.start();
    }

    private void showFunctionRecommend() {
        ThreadPool.postOnUiDelayed(new Runnable() {
            @Override
            public void run() {
                switch (getResultPageType()) {
                    case MultiCardPage:
                        startMultiCardAnim();
                        break;
                    case SingleCardPage:
                        cpuFullScreenLayout = findViewById(R.id.coolFullScreenLayout);
                        cpuContainer.setVisibility(View.GONE);
                        Bundle resultPageData = new Bundle();
                        resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.cup_cool_icon);
                        resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_ice);
                        resultPageData.putInt(ResultSingleCardLayout.COOL_COUNT, mCpuDropValue);
                        startSingleCardSceneAnim(SceneType.CPU_COOLER, resultPageData);

                        break;
                    default:
                        break;
                }
                changeTitle(MORE_SUGGSETION);
            }
        }, MARK_DELAY);
    }

    @Override
    public void onCpuScanFinished() {
        startShowCpuTemperature();
    }

    @Override
    public void onCpuCoolFinished() {

        if (isProtected || mIsNoApp) {
            if (isProtected) {
                mTemperatureDrop.setText(R.string.cpu_cooling_result_card_msg);
            } else {
                mTemperatureDrop.setText(R.string.no_process_optimized_result_msg);
            }
            ViewHelper.setAlpha(mTemperatureDrop, 0);
            mTemperatureDrop.setVisibility(View.VISIBLE);

            ObjectAnimator translateAnim = ObjectAnimator.ofFloat(mTemperatureDrop, "translationY",
                    -mTemperatureDropLength, 0);
            translateAnim.setDuration(400);
            ValueAnimator alpha = ObjectAnimator.ofFloat(mTemperatureDrop, "alpha", 0, 1);
            alpha.setDuration(400);

            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.play(translateAnim).with(alpha);
            animatorSet.start();

            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.FINISHED);
                    showFunctionRecommend();
                }
            });
        } else {
            ViewHelper.setAlpha(mTemperatureDropDegree, 0);
            mTemperatureDrop.setVisibility(View.VISIBLE);
            mTemperatureDropDegree.setVisibility(View.VISIBLE);

            ObjectAnimator translateAnim1 = ObjectAnimator.ofFloat(mTemperatureDrop,
                    "translationY", -mTemperatureDropLength, 0);
            translateAnim1.setDuration(400);
            ObjectAnimator translateAnim2 = ObjectAnimator.ofFloat(mTemperatureDropDegree,
                    "translationY", -mTemperatureDropLength, 0);
            translateAnim2.setDuration(400);
            ValueAnimator alpha2 = ObjectAnimator.ofFloat(mTemperatureDropDegree, "alpha", 0, 1);
            alpha2.setDuration(400);

            translateAnim1.start();
            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.play(translateAnim2).with(alpha2);
            animatorSet.setStartDelay(200);
            animatorSet.start();
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mCpuAnimatorView.switchStatus(CpuAnimatorView.Status.FINISHED);
                    showFunctionRecommend();
                }
            });
        }

        if (mAppIconListView != null) {
            mAppIconListView.setVisibility(View.GONE);
        }
        if (mStartButton != null) {
            mStartButton.setVisibility(View.GONE);
        }
    }
}
